package main

import (
	"flag"
	"github.com/gin-gonic/gin"
	qrcode "github.com/skip2/go-qrcode"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"path"
)

var (
	_e414 []byte
	_e501 []byte
	_e500 []byte
)

func init() {
	_file, _ := os.Getwd()

	{
		_f414, _err := ioutil.ReadFile(path.Join(_file, "414.png"))
		if nil != _err {
			log.Fatal(_err)
		}
		_e414 = _f414
	}

	{
		_f501, _err := ioutil.ReadFile(path.Join(_file, "501.png"))
		if nil != _err {
			log.Fatal(_err)
		}
		_e501 = _f501
	}

	{
		_f500, _err := ioutil.ReadFile(path.Join(_file, "500.png"))
		if nil != _err {
			log.Fatal(_err)
		}
		_e500 = _f500
	}
}

var (
	PARAM_MAX_LEN = flag.Int("PARAM_MAX_LEN", 2048, "")
)

/**
 *
 * @return
 */
func api_qrcode_get(c *gin.Context) {
	_param := c.Query("param")
	_len := len(_param)

	if 0 >= _len || *PARAM_MAX_LEN < _len {
		c.Writer.Write(_e414)
		return
	}

	_param, _err := url.QueryUnescape(_param)
	if nil != _err {
		c.Writer.Write(_e501)
		return
	}

	var _png []byte
	_png, _err = qrcode.Encode(_param, qrcode.Medium, 256)
	if nil != _err {
		c.Writer.Write(_e500)
		return
	}

	c.Writer.Write(_png)
}
